<template>
    <view class="add-form-container">
        <!-- 使用封装的页面头部组件 -->
        <page-header
            :title="isEdit ? '编辑病虫草害' : '新增病虫草害'"
        ></page-header>
        
        <!-- 使用地块选择器组件 -->
        <LandSelector
            ref="landSelector"
            @selection-change="handleLandSelectionChange"
        ></LandSelector>

        <!-- 使用条田选择器组件 -->
        <section-selector
            ref="sectionSelector"
            @areaChange="handleAreaChange"
            @usersChange="handleUsersChange"></section-selector>

        <view class="basic-info">
            <view class="section-title">基础信息</view>

            <uni-forms
                ref="form"
                :modelValue="formData"
                :rules="rules"
                validateTrigger="bind"
                label-position="top"
                label-width="200px"
                class="farm-form"
            >
                <uni-forms-item label="巡查时间" name="dateRange" required>
                    <uni-datetime-picker
                        type="daterange"
                        v-model="formData.dateRange"
                        :border="false"
                        :label-width="200"
                        @change="dateRangeChange"
                    >
                        <view class="uni-date-picker-container">
                            <text
                                :class="{
                                    placeholder: !formData.dateRangeText,
                                }"
                                >{{
                                    formData.dateRangeText || "请选择巡查时间"
                                }}</text
                            >
                            <view class="date-icon">
                                <roc-icon-plus
                                    type="fas"
                                    name="calendar-alt"
                                    :size="18"
                                    color="#999"
                                ></roc-icon-plus>
                            </view>
                        </view>
                    </uni-datetime-picker>
                </uni-forms-item>

                <uni-forms-item
                    label="病虫草害类型"
                    name="pestType"
                    :label-width="200"
                    required
                >
                    <uni-data-select
                        v-model="formData.pestType"
                        :localdata="pestTypesData"
                        placeholder="请选择类型"
                        @change="handlePestTypeChange"
                    ></uni-data-select>
                </uni-forms-item>

                <uni-forms-item label="病虫草害名称" name="pestNameId" required>
                    <uni-data-select
                        v-model="formData.pestNameId"
                        :localdata="currentPestNamesData"
                        placeholder="请选择名称"
                    ></uni-data-select>
                </uni-forms-item>

                <uni-forms-item label="灾害等级/程度" name="severityLevel" required>
                    <view class="severity-options">
                        <view 
                            class="severity-item" 
                            :class="{ active: formData.severityLevel === '2' }"
                            @click="formData.severityLevel = '2'"
                        >
                            <view class="severity-indicator mild"></view>
                            轻度
                        </view>
                        <view 
                            class="severity-item" 
                            :class="{ active: formData.severityLevel === '1' }"
                            @click="formData.severityLevel = '1'"
                        >
                            <view class="severity-indicator medium"></view>
                            中度
                        </view>
                        <view 
                            class="severity-item" 
                            :class="{ active: formData.severityLevel === '0' }"
                            @click="formData.severityLevel = '0'"
                        >
                            <view class="severity-indicator severe"></view>
                            重度
                        </view>
                    </view>
                </uni-forms-item>

                <uni-forms-item label="危害面积" name="area" required>
                    <uni-easyinput
                        type="digit"
                        v-model="formData.area"
                        placeholder="请输入危害面积"
                        disabled
                    >
                        <template #right>
                            <text class="input-unit">亩</text>
                        </template>
                    </uni-easyinput>
                </uni-forms-item>

                <!-- <uni-forms-item label="土地面积" name="landArea">
                    <uni-easyinput
                        type="digit"
                        v-model="formData.landArea"
                        placeholder="请输入土地面积"
                    >
                        <template #right>
                            <view class="unit-with-clear">
                                <text class="input-unit">亩</text>
                            </view>
                        </template>
                    </uni-easyinput>
                </uni-forms-item> -->

                <uni-forms-item label="处理方案" name="treatmentPlan">
                    <uni-easyinput
                        type="textarea"
                        v-model="formData.treatmentPlan"
                        placeholder="请输入处理方案"
                        :maxlength="200"
                    ></uni-easyinput>
                </uni-forms-item>

                <uni-forms-item label="负责人" name="personInCharge">
                    <uni-easyinput
                        v-model="formData.personInCharge"
                        placeholder="请输入负责人姓名"
                        disabled></uni-easyinput>
                </uni-forms-item>

                <uni-forms-item label="备注" name="remark">
                    <uni-easyinput
                        type="textarea"
                        v-model="formData.remark"
                        placeholder="请输入"
                        :maxlength="200"
                    ></uni-easyinput>
                </uni-forms-item>
            </uni-forms>
        </view>

        <view class="photo-section">
            <view class="section-title">现场照片</view>

            <image-uploader
                ref="imageUploader"
                :images="formData.images"
                :maxCount="9"
            />
        </view>
        
        <view class="submit-btn-container">
            <view class="submit-btn" @click="submitForm">确认提交</view>
        </view>
    </view>
</template>

<script>
import PageHeader from "@/components/PageHeader/index.vue";
import LandSelector from "@/components/LandSelector/index.vue";
import SectionSelector from "@/components/SectionSelector/index.vue";
import ImageUploader from "@/components/ImageUploader/index.vue";
import { pestDisease } from "@/utils/api/index.js";
import { formatDate, getDefaultDateRange } from "@/utils/util.js";
import { mapGetters, mapActions } from "vuex";

export default {
    components: {
        PageHeader,
        LandSelector,
        SectionSelector,
        ImageUploader,
    },
    computed: {
        ...mapGetters({
            getDictByType: "getDictByType",
            getDictLabel: "getDictLabel",
            userInfo: "getUserInfo"
        }),
    },
    data() {
        const defaultDateRange = getDefaultDateRange()
        return {
            isEdit: false,
            editId: null,
            formData: {
                dateRange: defaultDateRange.dateRange,
                dateRangeText: defaultDateRange.dateRangeText,
                pestType: "",
                pestNameId: "",
                severityLevel: "mild",
                area: "",
                landArea: "",
                treatmentPlan: "",
                personInCharge: "",
                personInId: "",
                remark: "",
                images: [],
                plotId: "",
                fieldId: "",
            },
            rules: {
                dateRange: {
                    rules: [
                        {
                            required: true,
                            errorMessage: "请选择巡查时间",
                        },
                    ],
                },
                pestType: {
                    rules: [
                        {
                            required: true,
                            errorMessage: "请选择病虫草害类型",
                        },
                    ],
                },
                pestNameId: {
                    rules: [
                        {
                            required: true,
                            errorMessage: "请选择病虫草害名称",
                        },
                    ],
                },
                severityLevel: {
                    rules: [
                        {
                            required: true,
                            errorMessage: "请选择灾害等级",
                        },
                    ],
                },
                area: {
                    rules: [
                        {
                            required: true,
                            errorMessage: "请输入危害面积",
                        },
                        {
                            format: "number",
                            errorMessage: "请输入有效的数字",
                        },
                    ],
                },
            },
            selectedLands: [],
            selectedSections: [],
            pestTypesData: [], // 病虫草害类型数据
            currentPestNamesData: [], // 当前选中类型的名称数据
        };
    },
    onLoad(options) {
       
        if (options.id) {
            this.isEdit = true;
            this.editId = parseInt(options.id);
            this.loadDiseaseData(this.editId);
        } else {
            // 设置默认的负责人和负责人ID
            console.log('用户信息', this.userInfo)
            this.formData.personInId = this.userInfo.id
            this.formData.personInCharge = this.userInfo.nickname
        }
        // 加载字典数据
        this.loadDictData();
    },
    methods: {
        ...mapActions(["getDictByType"]),

        // 加载字典数据
        async loadDictData() {
          console.log('获取字典问题1：')
            try {
                uni.showLoading({ title: "加载字典数据..." });

                // 加载病虫草害类型字典
                await this.getDictByType("pests_diseases_weeds_type");
                this.pestTypesData = this.formatDictToSelectData("pests_diseases_weeds_type");

                // 预加载各种类型的名称字典
                const pestTypes = this.getDictByType("pests_diseases_weeds_type");
                for (const pestType of pestTypes) {
                    if (pestType.value) {
                      console.log('获取字典问题2：'+pestType.value)
                        await this.getDictByType(pestType.value);
                    }
                }

                uni.hideLoading();
            } catch (error) {
                console.error("加载字典数据失败:", error);
                uni.hideLoading();
                uni.showToast({
                    title: "加载字典数据失败",
                    icon: "none",
                });
            }
        },

        // 将字典数据格式化为下拉选择框所需的格式
        formatDictToSelectData(dictType) {
            const dictList = this.getDictByType(dictType);
            return dictList.map((item) => ({
                value: item.value,
                text: item.label,
            }));
        },

        async loadDiseaseData(id) {
            try {
                uni.showLoading({ title: "加载中..." });

                // 调用API获取病虫草害记录详情
                const res = await pestDisease.getPestDiseaseDetail(id);

                if (res.code === 0 && res.data) {
                    const diseaseData = res.data;

                    // 设置日期范围
                    let startDate, endDate;
                    if (diseaseData.startDate) {
                        startDate = new Date(diseaseData.startDate);
                        endDate = diseaseData.endDate
                            ? new Date(diseaseData.endDate)
                            : new Date(diseaseData.startDate);
                    } else {
                        startDate = new Date(diseaseData.createTime);
                        endDate = new Date(diseaseData.createTime);
                        endDate.setDate(endDate.getDate() + 1);
                    }

                    this.formData = {
                        dateRange: [
                            startDate.toISOString().split("T")[0],
                            endDate.toISOString().split("T")[0],
                        ],
                        dateRangeText: `${formatDate(startDate)} 至 ${formatDate(endDate)}`,
                        pestType: diseaseData.pestType || "",
                        pestNameId: diseaseData.pestNameId || "",
                        severityLevel: diseaseData.severityLevel || "mild",
                        area: diseaseData.area ? diseaseData.area.toString() : "",
                        landArea: diseaseData.landArea ? diseaseData.landArea.toString() : "",
                        treatmentPlan: diseaseData.remarks || "",
                        personInCharge: diseaseData.personInCharge || "",
                        remark: diseaseData.remark || "",
                        images: this.formatImages(diseaseData.images),
                        plotId: diseaseData.plotId || "",
                        fieldId: diseaseData.fieldId || "",
                    };

                    // 初始化病虫草害名称下拉数据
                    this.handlePestTypeChange();

                    // 等待组件加载完成后，设置地块选择状态
                    this.$nextTick(() => {
                        setTimeout(() => {
                            // 设置地块选择器中选中的地块
                            if (this.$refs.landSelector && this.formData.plotId) {
                                this.$refs.landSelector.setSelectedLands(this.formData.plotId);
                                this.updateSelectedLands();

                                // 更新条田选择器的地块ID
                                if (this.$refs.sectionSelector) {
                                    this.$refs.sectionSelector.setSelectedParcels(this.selectedLands);

                                    // 设置条田选择状态
                                    if (this.formData.fieldId) {
                                        this.$refs.sectionSelector.setSelectedFields(this.formData.fieldId);
                                        this.updateSelectedSections();
                                    }
                                }
                            }
                        }, 1200);
                    });
                } else {
                    uni.showToast({
                        title: "获取数据失败",
                        icon: "none",
                    });
                }
                uni.hideLoading();
            } catch (error) {
                console.error("加载数据失败:", error);
                uni.hideLoading();
                uni.showToast({
                    title: "加载数据失败",
                    icon: "none",
                });
            }
        },

        // 格式化图片字段，将字符串转为数组
        formatImages(images) {
            if (!images) return [];
            if (typeof images === "string") {
                if (images.includes(",")) {
                    return images.split(",");
                }
                return [images];
            }
            return Array.isArray(images) ? images : [];
        },

        dateRangeChange(e) {
            if (e && e.length === 2) {
                const startDate = new Date(e[0]);
                const endDate = new Date(e[1]);
                this.formData.dateRangeText = `${formatDate(startDate)} 至 ${formatDate(endDate)}`;
            } else {
                this.formData.dateRangeText = "";
            }
        },

        async handlePestTypeChange() {
            console.log('根据选择的病虫草害类型，更新名称下拉选项1：'+this.formData.pestType)
            // 根据选择的病虫草害类型，更新名称下拉选项
            if (this.formData.pestType) {
                try {
                    // 根据选中的类型获取对应的名称字典
                    const pestTypeValue = this.formData.pestType;

                    // 从字典中获取对应的名称类型值
                    const pestTypeDict = this.getDictByType("pests_diseases_weeds_type");
                    const selectedPestType = pestTypeDict.find(
                        (item) => item.value === pestTypeValue
                    );

                    if (selectedPestType) {
                        // 加载对应的名称字典
                        await this.getDictByType(selectedPestType.value);
                        this.currentPestNamesData = this.formatDictToSelectData(selectedPestType.value);
                        console.log('根据选择的病虫草害类型，更新名称下拉选项2：')
                        console.log(this.currentPestNamesData)
                    } else {
                        this.currentPestNamesData = [];
                    }
                } catch (error) {
                    console.error("获取病虫草害名称字典失败:", error);
                    this.currentPestNamesData = [];
                }
            } else {
                this.currentPestNamesData = [];
            }

            // 重置名称
            if (
                this.formData.pestNameId &&
                !this.currentPestNamesData.some(
                    (item) => item.value === this.formData.pestNameId
                )
            ) {
                this.formData.pestNameId = "";
            }
        },

        handleLandSelectionChange() {
            this.updateSelectedLands();
        },

        handleAreaChange(area) {
            this.formData.area = area;
        },

        handleUsersChange(users) {
            this.formData.personInId = users.map((item) => item.userId).join(',');
            this.formData.personInCharge = users.map((item) => item.userName).join(',');
        },

        // 更新选中的地块数据
        updateSelectedLands() {
            if (this.$refs.landSelector) {
                this.selectedLands = this.$refs.landSelector.getSelectedLands();
                console.log("更新选中的地块:", this.selectedLands);

                // 当地块选择变化时，更新条田选择器
                if (this.$refs.sectionSelector) {
                    this.$refs.sectionSelector.setSelectedParcels(this.selectedLands);
                    // 更新选中的条田
                    this.updateSelectedSections();
                }
            }
        },

        // 更新选中的条田数据
        updateSelectedSections() {
            if (this.$refs.sectionSelector) {
                this.selectedSections = this.$refs.sectionSelector.getSelectedSections();
                console.log("更新选中的条田:", this.selectedSections);
            }
        },

        // 清空土地面积
        clearLandArea() {
            this.formData.landArea = "";
        },

        validateForm() {
            // 更新选中的地块和条田
            this.updateSelectedLands();
            this.updateSelectedSections();

            // 检查是否选择了地块
            if (!this.$refs.landSelector.validate()) {
                uni.showToast({
                    title: "请选择至少一个地块",
                    icon: "none",
                });
                return false;
            }

            // 检查是否选择了条田
            if (!this.$refs.sectionSelector.validate()) {
                uni.showToast({
                    title: "请选择至少一个条田",
                    icon: "none",
                });
                return false;
            }

            return true;
        },

        submitForm() {
            console.log(this.formData);
            // 使用uni-forms的验证方法
            this.$refs.form
                .validate()
                .then((result) => {
                    console.log("验证结果");
                    console.log(result);
                    console.log(this.validateForm());
                    if (this.validateForm()) {
                        this.submitFormData();
                    }
                })
                .catch((errors) => {
                    console.log("表单错误信息：", errors);
                });
        },

        async submitFormData() {
            try {
                // 获取选中的地块和条田
                this.updateSelectedLands();
                this.updateSelectedSections();

                let plotId = this.selectedLands.map((item) => item.id);
                let fieldId = this.selectedSections.map((item) => item.id);

                let plotName = this.selectedLands.map((item) => item.name);
                let fieldName = this.selectedSections.map((item) => item.name);
                console.log('提交表单1：');
                console.log(this.selectedLands, this.selectedSections);

                // 从imageUploader组件获取最新的图片列表
                const imageList = this.$refs.imageUploader.getImageList();

                // 构建提交的数据对象
                const submitData = {
                    id: this.isEdit ? this.editId : undefined,
                    startDate: this.formData.dateRange[0],
                    endDate: this.formData.dateRange[1],
                    plotId: plotId?.join(","), // 地块ID
                    fieldId: fieldId?.join(","), // 条田ID
                    plotName: plotName?.join(","), // 地块名称
                    fieldName: fieldName?.join(","), // 条田名称
                    area: parseFloat(this.formData.area),
                    pestType: this.formData.pestType,
                    pestTypeId: this.formData.pestType,
                    pestTypeName: this.getDictLabel("pests_diseases_weeds_type", this.formData.pestType),
                    // pestName: this.formData.pestName,
                    pestName: this.getDictLabel(this.formData.pestType, this.formData.pestNameId),
                    pestNameId: this.formData.pestNameId,
                    severityLevel: this.formData.severityLevel,
                    personInCharge: this.formData.personInCharge,
                    personInId: this.formData.personInId, // 根据实际需求设置
                    images: imageList.join(","), // 图片URL拼接
                    remarks: this.formData.treatmentPlan || "", // 处理方案作为备注说明
                    remark: this.formData.remark || "", // 备注
                };

                uni.showLoading({
                    title: "提交中...",
                });

                // 调用API创建或更新病虫草害记录
                let res;
                if (this.isEdit) {
                    res = await pestDisease.updatePestDiseaseRecord(submitData);
                } else {
                    res = await pestDisease.createPestDiseaseRecord(submitData);
                }

                uni.hideLoading();

                if (res.code === 0) {
                    uni.showToast({
                        title: this.isEdit ? "修改成功" : "添加成功",
                        icon: "success",
                        duration: 2000,
                        success: () => {
                            setTimeout(() => {
                                // 返回上一页并刷新
                                uni.navigateBack({
                                    delta: 1,
                                });
                            }, 1500);
                        },
                    });
                } else {
                    uni.showToast({
                        title: res.msg || "操作失败",
                        icon: "none",
                        duration: 2000,
                    });
                }
            } catch (error) {
                uni.hideLoading();
                console.error("提交数据失败:", error);
                uni.showToast({
                    title: "提交失败，请重试",
                    icon: "none",
                    duration: 2000,
                });
            }
        },
    },
};
</script>

<style lang="scss">
.severity-options {
    display: flex;
    gap: 20rpx;
    
    .severity-item {
        flex: 1;
        height: 80rpx;
        background-color: #f5f5f5;
        border-radius: 8rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
        color: #666;
        position: relative;
        
        &.active {
            &:nth-child(1) {
                background-color: #E8F5E9;
                color: #4CAF50;
                border: 1px solid #4CAF50;
            }
            
            &:nth-child(2) {
                background-color: #FFF3E0;
                color: #FF9800;
                border: 1px solid #FF9800;
            }
            
            &:nth-child(3) {
                background-color: #FFEBEE;
                color: #F44336;
                border: 1px solid #F44336;
            }
        }
        
        .severity-indicator {
            width: 16rpx;
            height: 16rpx;
            border-radius: 50%;
            margin-right: 8rpx;
            
            &.mild {
                background-color: #4CAF50;
            }
            
            &.medium {
                background-color: #FF9800;
            }
            
            &.severe {
                background-color: #F44336;
            }
        }
    }
}

.unit-with-clear {
    display: flex;
    align-items: center;
    gap: 10rpx;
    
    .clear-icon {
        font-size: 24rpx;
        color: #999;
        cursor: pointer;
    }
}
</style> 